import Vue from 'vue'
import axios from 'axios'
import elementUi from 'element-ui';
const apiURL = {
	baseURL: !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl,
	searchUrl: !window.searchUrl ? process.env.VUE_APP_SEARCHURL : window.searchUrl,
	aifaceUrl: !window.aifaceUrl ? process.env.VUE_APP_AIFACEURL : window.aifaceUrl,
	transcodeUrl: !window.transcodeUrl ? process.env.VUE_APP_TRANSCODEURL : window.transcodeUrl
}
let AccessToken = null;
let expirationTime = new Date().getTime();
axios.interceptors.request.use((config) => {
	let token = Vue.prototype.$local.get('token');
	if (config.headers.apiType === 2) {
		config.baseURL = apiURL.searchUrl;
	} else if (config.headers.apiType === 3) {
		config.baseURL = apiURL.aifaceUrl;
	} else if (config.headers.apiType === 4) {
		config.baseURL = apiURL.transcodeUrl;
	} else {
		config.baseURL = apiURL.baseURL;
	}
	if (!config.headers.noNeedLogin) {
		config.headers['Authorization'] = token;
	}
	if (!!token && config.url !== 'login') {
		let curTime = new Date().getTime();
		let userInfo = Vue.prototype.$local.get('userInfo');
		if (!!userInfo && userInfo.loginOutTime * 60 * 1000 < curTime - expirationTime) {
			Vue.prototype.$local.clear();
			window.location.reload();
		}
		expirationTime = new Date().getTime();
	}

	if (!!AccessToken && config.url === 'login') {
		config.headers['Access-Token'] = AccessToken;
	}

	//delete config.headers.apiType;
	//delete config.headers.noNeedLogin;
	return config
})

axios.interceptors.response.use((response) => {
	let { code, msg } = response.data;
	if (response.headers['access-token']) AccessToken = response.headers['access-token'];
	if (!!code && code !== '0') {
		if (msg === '用户身份验证失败' || msg === '您已经被强制下线,请重新登录' || msg === 'SESSION失效,请重新登录') {
			Vue.prototype.$showCustomMessage('warning', msg);
			Vue.prototype.$local.clear();
			window.location.reload();
		} else if (msg === '账号是封禁状态，请与管理员联系!') {
			Vue.prototype.$showCustomMessage('warning', '账号正在审核中,请耐心等候!');
		} else if (msg.indexOf('连续登录失败') !== -1) {
			let messArr = msg.split('-');
			Vue.prototype.$showCustomMessage('error', `${messArr[0]}，还需 ${messArr[1]} 秒才能再次登录`);
		} else {
			Vue.prototype.$showCustomMessage('warning', msg);
		}
	}
	return response
}, err => {
	return Promise.reject(err)
})

export default axios